import 'dart:async';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:read_flutter/common/Models.dart';
import 'package:read_flutter/common/ScreenUtils.dart';
import 'package:read_flutter/common/BookUtils.dart';
import 'package:read_flutter/common/SmartDrawer.dart';
import 'package:read_flutter/common/Tools.dart';
import 'package:scoped_model/scoped_model.dart';

class ReadPage extends StatefulWidget {
  ReadPage(this.bookContent, this.bookInfo, {this.con, Key key})
      : super(key: key);
  BookContent bookContent;
  BookInfo bookInfo;
  bool con = false;

  @override
  _ReadPageState createState() => _ReadPageState();
}

class _ReadPageState extends State<ReadPage> {
  BookContent bookContent;
  BookContent nextContent;
  BookContent lastContent;
  List<Map<String, int>> pagelength = [];
  List<String> bookPages = [];
  double fontSize;
  int backgroundColor;
  int textColor;
  bool showToolBar = false;
  int pageNum = 0;
  bool firstSetup = true;
  ReadApiModels models;
  bool showFontSizeWidget = false;
  List<BookContent> catalogList = [];
  bool isLoading = false;

  GlobalKey _myKey = new GlobalKey();
  GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey();

//  GlobalKey _catalogListView = new GlobalKey();

  var _ctl = new ScrollController();
  GlobalKey _listViewKey = new GlobalKey();

  @override
  initState() {
    super.initState();
  }

  getBookContent() async {
    bookContent = await bookContentProvider()
        .getBookContentWithLink(widget.bookContent.link);
    print(bookContent.link);
    if (bookContent.content == null) {
      downloadContent(bookContent);
      setState(() {
        isLoading = true;
      });
    } else {
      setupContent();
    }
  }

  reloadText() async {
    double h = _myKey.currentContext.size.height;
    double w = _myKey.currentContext.size.width;
    bookPages = [];
    pagelength = await ReadUtils().getPageList(
        bookContent.content, h, ScreenUtils.ScreenW - 20, models.fontSize);
    for (Map<String, int> map in pagelength) {
      bookPages.add(bookContent.content.substring(map["start"], map["end"]));
    }
  }

  setupContent() async {
    if (bookContent.content == null) {
      downloadContent(bookContent);
      setState(() {
        isLoading = true;
      });
    } else {
//    RenderObject renderObject = _myKey.currentContext.findRenderObject();
      double h = _myKey.currentContext.size.height;
      double w = _myKey.currentContext.size.width;
      bookPages = [];
      pagelength = await ReadUtils().getPageList(
          bookContent.content, h, ScreenUtils.ScreenW - 20, models.fontSize);
//    for (int i = 0; i < bookContent.content.length; i++) {
//      if ((i + 1) * pagelength > bookContent.content.length) {
//        bookPages.add(bookContent.content
//            .substring(i * pagelength, bookContent.content.length));
//        break;
//      }
//      bookPages.add(bookContent.content
//          .substring(i * pagelength, (i + 1) * pagelength));
//    }

      for (Map<String, int> map in pagelength) {
        bookPages.add(bookContent.content.substring(map["start"], map["end"]));
      }
      if (pageNum == -1) {
        pageNum = bookPages.length - 1;
        print(bookPages.length);
      }
      if (firstSetup && widget.con != null && widget.con) {
        firstSetup = false;
        int key = widget.bookInfo.keyword;
        for (int p = 0; p < pagelength.length; p++) {
          Map<String, int> map = pagelength[p];
          if (key >= map["start"] && key < map["end"]) {
            pageNum = p;
            break;
          }
        }
      }
      isLoading = false;
      showToolBar = false;
      setState(() {});

      nextContent = await bookContentProvider().getBookContentBookidAndIndex(
          widget.bookInfo.id, bookContent.chapterindex + 1);
      if (nextContent != null) {
        if (nextContent != null && nextContent.content == null) {
          downloadContent(nextContent);
        }
      }

      if (bookContent.chapterindex != 0) {
        lastContent = await bookContentProvider().getBookContentBookidAndIndex(
            widget.bookInfo.id, bookContent.chapterindex - 1);
        if (lastContent != null && lastContent.content == null) {
          downloadContent(lastContent);
        }
      }
    }
  }

  downloadContent(BookContent content) async {
    Response res = await Tools().request(
        "/search/getcontent", {"link": content.link, "source": content.source});

    if (res.data["code"] == "0") {
      content.content = res.data['result']['Content'];
      bookContentProvider().update(content);
      setupContent();
//      }
    } else {
      Tools().showToast("加载章节内容失败");
    }
  }

  Widget topBar() {
    return Container(
      height: 20.0,
      padding: EdgeInsets.symmetric(horizontal: 5),
      width: double.infinity,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            widget.bookInfo.showname,
            style: TextStyle(fontSize: 10, color: Color(models.textColor)),
          ),
          Text(
            bookContent == null
                ? widget.bookContent.chaptername
                : bookContent.chaptername,
            style: TextStyle(fontSize: 10, color: Color(models.textColor)),
          )
        ],
      ),
    );
  }

  Widget reader() {
    if (fontSize == null) {
      fontSize = models.fontSize;
    }
    return Expanded(
        child: Container(
      margin: EdgeInsets.symmetric(vertical: 5),
      key: _myKey,
      width: ScreenUtils.ScreenW - 20,
      child: Text(
        bookPages.length > 0 ? bookPages[pageNum] : "正在获取",
        style: TextStyle(
            fontSize: models.fontSize, color: Color(models.textColor)),
      ),
    ));
  }

//  Widget bottomBar() {
//    return Container(
//      height: 20.0,
//      width: double.infinity,
//      margin: EdgeInsets.symmetric(horizontal: 20),
//    );
//  }

  Widget tapWidget() {
    return Container(
      height: double.infinity,
      width: double.infinity,
      child: Row(
        children: <Widget>[
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            child: Container(
              height: double.infinity,
              width: ScreenUtils.ScreenW / 3,
            ),
            onTap: () async {
              print("上一页");
              if (pageNum != 0) {
                pageNum--;
                setState(() {});
              } else {
                if (lastContent == null) {
                  Tools().showToast("没有前一章了");
                } else {
                  pageNum = -1;
                  bookContent = lastContent;
//                  lastContent = null;
//                  nextContent = null;
                  await setupContent();
                }
              }
              print("保存进度");
              saveKeyWord();
            },
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            child: Container(
              width: ScreenUtils.ScreenW / 3,
              height: double.infinity,
            ),
            onTap: () {
              setState(() {
                showToolBar = !showToolBar;
              });
            },
          ),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            child: Container(
              width: ScreenUtils.ScreenW / 3,
              height: double.infinity,
            ),
            onTap: () async {
//              print("下一页");
//              print(pageNum);
//              print(bookPages.length);

              if (pageNum < bookPages.length - 1) {
                pageNum++;
                setState(() {});
              } else {
                if (nextContent == null) {
                  Tools().showToast("最后一章了");
                } else {
                  pageNum = 0;
                  bookContent = nextContent;
//                  nextContent = null;
//                  lastContent = null;
                  await setupContent();
                }
              }
              saveKeyWord();
            },
          )
        ],
      ),
    );
  }

  saveKeyWord() {
    BookInfo temp = widget.bookInfo;
    temp.lastUrl = bookContent.link;
    temp.keyword = pagelength[pageNum]["start"];
    temp.lastread = (DateTime.now().millisecondsSinceEpoch / 1000).toString();
    print(temp.keyword);
    BookInfoProvider().update(temp);
  }

  Widget coverWidget() {
//    print(showToolBar ? "显示" : "隐藏");
    return Offstage(
      offstage: !showToolBar,
      child: Column(
        children: <Widget>[
          topToolBar(),
          Expanded(child: Container()),
          bottomToolBar()
        ],
      ),
    );
  }

  Widget topToolBar() {
    return Container(
      width: double.infinity,
      color: Color(0xcc000000),
      height: 10 + ScreenUtil.statusBarHeight,
      padding: EdgeInsets.only(bottom: 10.0),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          GestureDetector(
            child: Container(
              child: Icon(
                Icons.arrow_back_ios,
                color: Colors.white,
                size: 25,
              ),
              margin: EdgeInsets.only(left: 10),
            ),
            onTap: () {
              saveKeyWord();
              Navigator.of(context).pop();
            },
          ),
          Expanded(
              child: Container(
            child: Text(
              bookContent == null
                  ? widget.bookContent.chaptername
                  : bookContent.chaptername,
              softWrap: false,
              overflow: TextOverflow.fade,
              style: TextStyle(fontSize: 20, color: Colors.white),
            ),
          )),
          GestureDetector(
            child: Container(
              margin: EdgeInsets.only(right: 10),
//              child: Icon(
//                Icons.headset,
//                color: Colors.white,
//                size: 30,
//              ),
            ),
          )
        ],
      ),
    );
  }

  Widget bottomToolBar() {
    return Container(
      width: double.infinity,
      color: Color(0xcc000000),
      padding: EdgeInsets.only(top: 10),
      height: 60,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <Widget>[
          GestureDetector(
              child: Container(
                child: Icon(
                  Icons.list,
                  color: Colors.white,
                  size: 30,
                ),
              ),
              onTap: () {
                _scaffoldKey.currentState.openDrawer();
              }),
          GestureDetector(
            child: Container(
              child: Text("A-",
                  style: TextStyle(
                      color:
                          models.fontSize > 14 ? Colors.white : Colors.blueGrey,
                      fontSize: 26)),
            ),
            onTap: () {
              print(models.fontSize);
              if (models.fontSize > 14) {
                models.updateFontSize(models.fontSize - 1);
                reloadText();
              }
            },
          ),
          GestureDetector(
            child: Container(
              child: Text("A+",
                  style: TextStyle(
                      color:
                          models.fontSize < 26 ? Colors.white : Colors.blueGrey,
                      fontSize: 26)),
            ),
            onTap: () {
              print(models.fontSize);
              if (models.fontSize < 26) {
                models.updateFontSize(models.fontSize + 1);
                reloadText();
              }
            },
          ),
          GestureDetector(
            child: Container(
              child: Icon(
                models.night ? Icons.wb_sunny : Icons.brightness_2,
                color: Colors.white,
                size: 30,
              ),
            ),
            onTap: () {
              models.updateNight(!models.night);
            },
          )
        ],
      ),
    );
  }

  Widget catalogListWidget() {
    return Container(
        key: _listViewKey,
        child: ListView.builder(
          controller: _ctl,
          key: new PageStorageKey("catalog"),
          padding: EdgeInsets.only(top: 0, bottom: 20),
          itemBuilder: (BuildContext context, int index) {
            return catalogItem(index);
          },
          itemCount: catalogList.length,
        ));
  }

  Widget drawerWidget() {
    print("aaaa");

    return SmartDrawer(
      child: Container(
        color: Color(0xcc000000),
        child: Column(
          children: <Widget>[
            drawerHeader(),
            Expanded(
//              child: NotificationListener<ScrollUpdateNotification>(
//            onNotification: (notification) {
//              getVisible();
//              return true;
//            },
              child: catalogListWidget(),
            )
          ],
        ),
      ),
      callback: (open) {
        print(open ? "打开" : "关闭");
        if (open) {
          Future.delayed(const Duration(milliseconds: 500),
              () => jumpTo(bookContent.chapterindex));
        }
      },
    );
  }

  jumpTo(index) {
    double o = 30.0 * index;
    int last = catalogList.length-index;
    if (last * 30<_listViewKey.currentContext.size.height){
      o = 30 * catalogList.length - _listViewKey.currentContext.size.height;
    }
    print(o);
//    _ctl.jumpTo(o);
    _ctl.animateTo(o, duration: Duration(milliseconds: 200), curve: Curves.linear);
  }

  Widget catalogItem(int index) {
    BookContent temp = catalogList[index];
    return GestureDetector(
      child: Container(
        height: 20,
        margin: EdgeInsets.symmetric(vertical: 5.0, horizontal: 5.0),
        child: Text(
          temp.chaptername,
          style: TextStyle(
              color: temp.id == bookContent.id ? Colors.blue : Colors.white,
              fontSize: 13.0),
        ),
      ),
      onTap: () {
        if (bookContent.id != temp.id) {
          Navigator.pop(context);
          bookContent = temp;
          lastContent = null;
          nextContent = null;
          pageNum = 0;
          if (temp.content == null) {
            downloadContent(temp);
            setState(() {
              isLoading = true;
            });
          } else {
            setupContent();
          }
        }
      },
    );
  }

  Widget drawerHeader() {
    return GestureDetector(
      child: Container(
        width: double.infinity,
        height: 100 + ScreenUtil.statusBarHeight,
        color: Colors.black12,
        padding:
            EdgeInsets.only(top: 100.0, left: 15.0, right: 10.0, bottom: 10.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              child: Image(
                image: CachedNetworkImageProvider(widget.bookInfo.imagelink),
                fit: BoxFit.contain,
                width: ScreenUtil().setWidth(200),
                height: ScreenUtil().setWidth(275),
              ),
            ),
            Container(
              child: Text(
                widget.bookInfo.showname,
                style: TextStyle(fontSize: 30, color: Colors.white),
              ),
            ),
          ],
        ),
      ),
      onTap: () {},
    );
  }

  getCatalogList() async {
    catalogList = await bookContentProvider()
        .getBookContentListWithBookID(widget.bookInfo.id);

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    if (bookContent == null) {
      getBookContent();
      getCatalogList();
    }
    return ScopedModelDescendant<ReadApiModels>(
        builder: (context, child, model) {
      models = model;
      return Scaffold(
        key: _scaffoldKey,
        body: Container(
            color: Color(models.backgroundColor),
            child: Stack(
              children: <Widget>[
                SafeArea(
//                bottom: false,
                  left: false,
                  right: false,

                  child: Container(
                    padding: EdgeInsets.only(bottom: 20),
                    child: Column(
                      children: <Widget>[topBar(), reader()],
                    ),
                  ),
                ),
                tapWidget(),
                coverWidget(),
                loadProgressHUD()
              ],
            )),
        drawer: drawerWidget(),
      );
    });
  }

  loadProgressHUD() {
    return Offstage(
      offstage: !isLoading,
      child: Container(
          width: double.infinity,
          height: double.infinity,
          color: Color.fromRGBO(0, 0, 0, 0.7),
          child: Center(
              child: Container(
            width: 80.0,
            height: 80.0,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: <Widget>[
                SpinKitCircle(
                  color: Colors.blue,
                  size: 25.0,
                ),
              ],
            ),
          ))),
    );
  }
}
